package org.NooLab.itexx.app.controller.content;

import java.io.Serializable;
import java.util.ArrayList;

import org.NooLab.itexx.ITexxWindowCommons;
import org.NooLab.utilities.files.DFutils;
import org.NooLab.utilities.logging.PrintLog;
import org.NooLab.utilities.strings.ArrUtilities;
import org.NooLab.utilities.strings.StringsUtil;



public class SearchEngines implements Serializable{

	
	ArrayList<SearchEngine> items = new ArrayList<SearchEngine>();
	
	transient ITexxWindowCommons appCommons;
	
	
	transient StringsUtil strgutil = new StringsUtil();
	transient DFutils fileutil = new DFutils();
	transient ArrUtilities arrutil = new ArrUtilities();
	transient PrintLog out = new PrintLog(2,false);

	// ========================================================================
	public SearchEngines(ITexxWindowCommons commons){
		appCommons = commons;
	}
	// ========================================================================

	
	public SearchEngine getNewEngine(int insertToList) {
		
		SearchEngine se = new SearchEngine(this);
		
		if (insertToList>=1){
			items.add(se) ;
		}
		
		return se;
	}

	
	public ArrayList<SearchEngine> getItems() {
		return items;
	}

	public void setItems(ArrayList<SearchEngine> items) {
		this.items = items;
	}
	
	public int size(){
		return items.size();
	}
	
	public SearchEngine get(int index){
		SearchEngine se = null;
		
		if ((index>=0) && (index<items.size())){
			se = items.get(index);
		}
		
		return se;
	}

	public ArrayList<SearchEngine> getActives(){
		ArrayList<SearchEngine> ase = new ArrayList<SearchEngine>();
		
		for (int i=0;i<items.size();i++){
			if (items.get(i).isActive()){
				ase.add(items.get(i));
			}
		}
		return ase;
	}
	
	public int getIndexByName( String pattern, boolean onlyActive, boolean relaxed){
		int index=-1;
		boolean hb;
		SearchEngine item;
		
		for (int i=0;i<items.size();i++){
			hb = true;
			item = items.get(i);
			if (onlyActive){
				hb = item.isActive();
			}
			
			if (hb){
				String name = item.getName();
				
				if (relaxed){
					hb = (name.contains(pattern.toLowerCase())) ; 
				}else{
					hb = name.contentEquals(pattern) ;
				}
			} // hb ->
			if (hb){
				index=i;
				break;
			}
		}// i ->
		
		
		return index;
	}


	public SearchEngine getSearchEngineByUrl(String urlstr) {
		// 
		SearchEngine seItem = null;
		
		urlstr = strgutil.getDomainFromUrl(urlstr).toLowerCase() ;
		
		urlstr = urlstr.replace("www.", "");
		urlstr = urlstr.replace("http://", "");
		int p = urlstr.indexOf(".");
		if (p>0){
			urlstr = urlstr.substring(0,p);	
		}
		
		int ix = this.getIndexByName(urlstr, true, true) ;
		
		if (ix>=0){
			seItem = items.get(ix) ;
		}
		return seItem;
	}
	
	

	
}
